import React, { Component } from 'react'
import './index.scss'
import { NavBar, Toast, Image, Tag, Popup } from 'antd-mobile'
import { getCityCurrent } from 'utils/storage'
import { getAreaInfo } from 'api/city'
import { getHouseInfo } from 'api/houses'
import { BASE_URL } from 'utils/url'
export default class Map extends Component {
  componentDidMount() {
    this.initMap()
  }
  state = {
    visiblePopup: false,
    list: [],
  }
  initMap = () => {
    // 初始化地图实例
    // 在react中脚手架全局对象需要使用window来访问
    const { label, value } = getCityCurrent()
    const map = new window.BMapGL.Map('container')
    this.map = map
    //创建地址解析器实例
    const myGeo = new window.BMapGL.Geocoder()
    // 将地址解析结果显示在地图上，并调整地图视野
    myGeo.getPoint(
      label,
      async (point) => {
        if (point) {
          map.centerAndZoom(point, 11)
          map.addControl(new window.BMapGL.ZoomControl())
          map.addControl(new window.BMapGL.ScaleControl())
          // 在map对象上调用 addOverlay 方法 将文本覆盖物添加到地图
          this.renderOverlays(value)
        } else {
          Toast.fail('您选择的地址没有解析到结果！')
        }
      },
      label
    )
  }
  // 发请求拿数据
  async renderOverlays(id) {
    const { body: res } = await getAreaInfo(id)
    // 调用getTypeAndZoom 获取缩放级别和类型
    const { nextZoom, type } = this.getTypeAndZoom()
    res.forEach((item) => {
      // 创建覆盖物
      this.createOverlays(item, nextZoom, type)
    })
  }
  // 地图缩放比
  // 区 11  范围 >= 10 < 12
  // 镇 13  范围 >= 12 < 14
  // 小区 15  范围 >= 14 < 16
  getTypeAndZoom() {
    const zoom = this.map.getZoom()
    let nextZoom, type
    if (zoom >= 10 && zoom < 12) {
      type = 'circle'
      nextZoom = 13
    } else if (zoom >= 12 && zoom < 14) {
      nextZoom = 15
      type = 'circle'
    } else if (zoom >= 14 && zoom < 16) {
      type = 'rect'
    }
    return { type, nextZoom }
  }

  createOverlays(data, zoom, type) {
    const {
      coord: { latitude, longitude },
      label: areaName,
      count,
      value,
    } = data
    const areaPoint = new window.BMapGL.Point(longitude, latitude)
    if (type === 'circle') {
      // 区或镇
      this.createCircle(areaPoint, areaName, count, value, zoom)
    } else {
      // 小区
      this.createRect(areaPoint, areaName, count, value)
    }
  }

  // 创建区覆盖物
  createCircle(point, name, count, id, zoom) {
    const label = new window.BMapGL.Label('', {
      position: point,
      offset: new window.BMapGL.Size(-35, -35),
    })
    label.id = id
    label.setContent(`
    <div class="bubble">
    <p class="name">${name}</p>
    <p>${count}套</p>
    </div>
    `)
    // 设置样式
    label.setStyle({
      cursor: 'pointer',
      border: '0px solid rgb(255,0,0)',
      padding: '0px',
      whiteSpace: 'nowrap',
      fontSize: '12px',
      color: 'rbg(255,255,255)',
      textAlign: 'center',
    })
    // 添加点击事件
    label.addEventListener('click', () => {
      // 调用 renderOverlays 获取该区域下的房源数据
      this.renderOverlays(id)
      // 添加覆盖物到地图
      this.map.centerAndZoom(point, zoom)
      // 解决清除覆盖物时 百度地图API的JS 文件自身报错的问题
      setTimeout(() => {
        this.map.clearOverlays()
      }, 0)
    })
    // 添加覆盖物到地图中
    this.map.addOverlay(label)
  }

  // 创建小区的覆盖物
  createRect(point, name, count, id) {
    const label = new window.BMapGL.Label('', {
      position: point,
      offset: new window.BMapGL.Size(-50, -28),
    })
    label.id = id

    label.setContent(`
    <div class="rect">
       <span class="housename">${name}</span>
       <span class="housenum">${count}套</span>
       <i class="arrow"></i>
    </div>
    `)
    // 设置样式
    label.setStyle({
      cursor: 'pointer',
      border: '0px solid rgb(255,0,0)',
      padding: '0px',
      whiteSpace: 'nowrap',
      fontSize: '12px',
      color: 'rbg(255,255,255)',
      textAlign: 'center',
    })
    // 添加点击事件
    label.addEventListener('click', (e) => {
      this.getHousesList(id)
      const target = e.domEvent.changedTouches[0]
      this.map.panBy(
        window.innerWidth / 2 - target.clientX,
        (window.innerHeight - 375) / 2 - target.clientY
      )
    })
    // 添加覆盖物到地图中
    this.map.addOverlay(label)
  }

  // 获取小区房源数据
  async getHousesList(id) {
    const { body: res } = await getHouseInfo(id)
    this.setState({
      visiblePopup: true,
      list: res.list,
    })
  }

  render() {
    const { list, visiblePopup } = this.state
    return (
      <div className="map">
        <NavBar onBack={() => this.props.history.go(-1)}>地图找房</NavBar>
        <div id="container"></div>
        <Popup
          visible={visiblePopup}
          onMaskClick={() => this.setState({ visiblePopup: false })}
          bodyStyle={{ maxHeight: '40vh', overflow: 'auto', minHeight: '40vh' }}
        >
          <div className="houseInfo">
            <div className="title">
              <h2>房屋列表</h2>
              <span>更多房源</span>
            </div>
            <ul className="cont">
              {list.map((item) => (
                <li key={item.houseCode}>
                  <Image src={BASE_URL + item.houseImg} fit="cover" />
                  <div className="house_text">
                    <h3>{item.title}</h3>
                    <p>{item.desc}</p>
                    {item.tags.map((tag) => (
                      <Tag
                        key={tag}
                        color="primary"
                        style={{ marginRight: '5px' }}
                      >
                        {tag}
                      </Tag>
                    ))}

                    <h3 className="price">
                      {item.price} <span>元/月</span>
                    </h3>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        </Popup>
      </div>
    )
  }
}
